package zp.history.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import zp.history.R;
import zp.history.util.Log;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DbAdapter {

	private String DATABASE_PATH;

	private String DATABASE_FILENAME;

	private Resources resources;

	private SQLiteDatabase db;

	public static final String KEY_ID = "_id";

	public static final String KEY_DATE = "date";

	public static final String KEY_CONTENT = "content";

	public DbAdapter(String DATABASEPATH, String DATABASEFILENAME,
			Resources resources) {
		super();
		this.DATABASE_PATH = DATABASEPATH;
		this.DATABASE_FILENAME = DATABASEFILENAME;
		this.resources = resources;
		this.db = openDatabase();
	}

	private SQLiteDatabase openDatabase() {
		try {
			String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
			Log.i("database path:" + databaseFilename);
			File dir = new File(DATABASE_PATH);

			if (!dir.exists())
				dir.mkdir();

			if (!(new File(databaseFilename)).exists()) {
				InputStream is = resources.openRawResource(R.raw.history);
				FileOutputStream fos = new FileOutputStream(databaseFilename);
				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}

				fos.close();
				is.close();
			}

			SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
					databaseFilename, null);

			return database;
		} catch (Exception e) {
			Log.i(e.toString());
		}
		return null;
	}

	public void close() {
		db.close();
	}

	public Cursor getItems(String date) {
		String sql = "select _id,date,content from history where date like '____"
				+ date.substring(4) + "' order by date desc";
		Log.i("sql:" + sql);
		if (db == null)
			openDatabase();

		return db.rawQuery(sql, null);
	}

}
